package io.aggression.test.security;

import io.aggression.test.cache.UserCache;
import io.aggression.test.model.User;
import io.aggression.test.util.Security;
import io.undertow.security.idm.Account;
import io.undertow.security.idm.Credential;
import io.undertow.security.idm.DigestCredential;
import io.undertow.security.idm.IdentityManager;
import java.security.MessageDigest;

public class MongoIdentityManager implements IdentityManager {


    private UserCache userCache = null;

    public MongoIdentityManager(){

        //instantiate user cache
        userCache = new UserCache.Builder()
                .server("localhost").build();
    }


    @Override
    public Account verify(Account account) {
        System.out.println("Hello 1");
        return null;
    }

    @Override // Regular http basic authentication
    public Account verify(String userId, Credential credential) {

        if( userCache.userIdExists(userId) ){
            User u = userCache.loadUser(userId);
           System.out.println("Successful auth");
	   System.out.println("Clear Data: " + userId + ":" + "AggressionLabs" + ":" + u.getPassword());
           System.out.println("CredType: " + credential);

try {
	   MessageDigest md = MessageDigest.getInstance("MD5");
	   String x = userId + ":" + "AggressionLabs" + ":" + u.getPassword();
	   md.update(x.getBytes());

           System.out.println("Browser digest verify: " + ((DigestCredential)credential).verifyHA1(x.getBytes()) );
           System.out.println("Server side digest: " + md.digest() );

           //	System.out.println("CredType: " + credential.);
	   //
	   }catch(Exception e ){System.out.println("ERROR");}
           return Security.getAccountFromUser(u);
        }
        else return null;
    }

    @Override
    public Account verify(Credential credential) {
        System.out.println("Hello 3");
        return null;
    }
}

